package cn.wikiflyer.beikang.act;

import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;

import net.tsz.afinal.annotation.view.ViewInject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.wikiflyer.beikang.BaseActivity;
import cn.wikiflyer.beikang.IApplication;
import cn.wikiflyer.beikang.R;
import cn.wikiflyer.beikang.act.user.UserAddressListAct;
import cn.wikiflyer.beikang.act.user.UserChangePhoneAct;
import cn.wikiflyer.beikang.act.user.UserInComeOrderListAct;
import cn.wikiflyer.beikang.act.user.UserKnowBeikangAct;
import cn.wikiflyer.beikang.act.user.UserNoticeListAct;
import cn.wikiflyer.beikang.act.user.UserOrderListAct;
import cn.wikiflyer.beikang.act.user.UserShareAct;
import cn.wikiflyer.beikang.act.user.UserTiXianListAct;
import cn.wikiflyer.beikang.act.user.UserVipListAct;
import cn.wikiflyer.beikang.act.user.UserYongJinListAct;
import cn.wikiflyer.beikang.act.user.avator.Avator;
import cn.wikiflyer.beikang.act.user.setting.UserSettingAct;
import cn.wikiflyer.beikang.act.user.utils.VipPopWindow;
import cn.wikiflyer.beikang.bean.base.BKBaseBean;
import cn.wikiflyer.beikang.utils.BKUploadUtil;
import cn.wikiflyer.beikang.utils.BKUploadUtil.UploadCallBack;
import cn.wk.libs4a.WKApplication;
import cn.wk.libs4a.net.WKAsyncTaskPro;
import cn.wk.libs4a.utils.L;
import cn.wk.libs4a.utils.WKPhotoUtil;
import cn.wk.libs4a.utils.WKPhotoUtil.IImageCallBack;
import cn.wk.libs4a.utils.alipay.Base64;
import cn.wk.libs4a.view.WKCircleImageView;
import cn.wk.libs4a.view.WKHeader;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.utils.Log;

/**
 * 个人中心
 * 
 * @author qunlee_mr
 * 
 */
public class TabUserAct extends BaseActivity implements OnClickListener {

	@ViewInject(id = R.id.header)
	private WKHeader header;

	@ViewInject(id = R.id.upgrade_linear, click = "onClick")
	private LinearLayout upgrade_linear;

	@ViewInject(id = R.id.is_upgrade, click = "onClick")
	// 是否达到晋升的标准提示TextView
	private TextView is_upgrade;

	@ViewInject(id = R.id.center_img, click = "onClick")
	private WKCircleImageView image;

	@ViewInject(id = R.id.center_name)
	private TextView center_name;

	@ViewInject(id = R.id.center_vip, click = "onClick")
	private TextView center_vip;
	@ViewInject(id = R.id.textView_know, click = "onClick")
	private TextView tv_know;// 了解会员按钮

	// @ViewInject(id = R.id.center_money, click = "onClick")
	// private LinearLayout center_money;

	@ViewInject(id = R.id.center_money_tixian, click = "onClick")
	private LinearLayout center_money_tixian;

	@ViewInject(id = R.id.center_money_yongjin, click = "onClick")
	private LinearLayout center_money_yongjin;

	@ViewInject(id = R.id.center_cash)
	private TextView center_cash;
	@ViewInject(id = R.id.center_balance)
	private TextView center_balance;
	@ViewInject(id = R.id.center_unclear)
	private TextView center_unclear;

	private String urlUpAvator = "";

	private Intent intent;

	@ViewInject(id = R.id.user_leftmoney)
	private TextView user_leftmoney;

	@Override
	public void loadXml() {
		setContentView(R.layout.bk_act_user_tab);
		initSize();
	}

	@Override
	public void init() {
		upgrade_linear.setVisibility(View.GONE);
		header.setLeftImg("设置", R.drawable.user_setting_img, false, 12);
		header.setClickListener(null, null, new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ctx, UserSettingAct.class);
				startActivity(intent);

				// mUserBean.level = "1";
				// showLevelUpView();

			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		// if (app().getLoginSession() != null) {
		new GetUserInfo(this);
		// } else {
		// mUserBean = null;
		// app().userInfo = null;
		// updateUI();
		// }
	}

	@Override
	public void setData() {
	}

	public void onClick(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.upgrade_linear:
			break;
		case R.id.center_img:
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			new GetAvatorUrl(ctx);
			// new Avator(activity).showSelection(view);;
			break;
		case R.id.textView_know: // 点击了解会员按钮
			// Toast.makeText(ctx, "了解会员", Toast.LENGTH_SHORT).show();
			new VipPopWindow(ctx, width, height).show();
			break;
		case R.id.is_upgrade:
			// WKApplication.showMsg("会员晋升");
			showLevelUpView();
			break;
		case R.id.close_upgrade:
			// WKApplication.showMsg("关闭晋升通知");
			upgrade_linear.setVisibility(View.GONE);
			break;
		case R.id.center_money_yongjin:
			// WKApplication.showMsg("佣金列表");
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			intent = new Intent(ctx, UserYongJinListAct.class);
			intent.putExtra("bean", mUserBean);
			startActivity(intent);
			break;
		case R.id.center_money_tixian:
			// WKApplication.showMsg("提现列表");
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			intent = new Intent(ctx, UserTiXianListAct.class);
			intent.putExtra("bean", mUserBean);
			startActivity(intent);
			break;
		case R.id.center_vip:
			// WKApplication.showMsg("乐享会员");
			break;
		case R.id.center_grid1: // 通知列表
			// WKApplication.showMsg("我的通知");
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			intent = new Intent(ctx, UserNoticeListAct.class);
			startActivity(intent);
			break;
		case R.id.center_grid2:
			// WKApplication.showMsg("我的订单");
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			intent = new Intent(ctx, UserOrderListAct.class);
			intent.putExtra("bean", mUserBean);
			startActivity(intent);
			break;
		case R.id.center_grid3:
			// WKApplication.showMsg("收入订单");
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			intent = new Intent(ctx, UserInComeOrderListAct.class);
			intent.putExtra("userbean", mUserBean);
			startActivity(intent);
			break;
		case R.id.center_grid4:
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			// WKApplication.showMsg("地址管理");
			intent = new Intent(ctx, UserAddressListAct.class);
			startActivity(intent);
			break;
		case R.id.center_grid5:
			// WKApplication.showMsg("会员体系");
			if (app().getLoginSession() == null) {
				IApplication.showToast("" + IApplication.loginTxt);
				return;
			}
			intent = new Intent(ctx, UserVipListAct.class);
			startActivity(intent);
			break;
		case R.id.center_grid6:
			// WKApplication.showMsg("更换手机");
			intent = new Intent(ctx, UserChangePhoneAct.class);
			startActivity(intent);
			break;
		case R.id.center_grid7: // 了解倍康
			intent = new Intent(ctx, UserKnowBeikangAct.class);
			startActivity(intent);
			break;
		case R.id.center_grid8:
			// WKApplication.showMsg("推荐好友");
			intent = new Intent(ctx, UserShareAct.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private UserInfoBean mUserBean;

	private void checkLevel() {
		if (app().getLoginSession() == null) {
			upgrade_linear.setVisibility(View.GONE);
			return;
		}
		if (mUserBean == null) {
			upgrade_linear.setVisibility(View.GONE);
			return;
		}
		if (!mUserBean.upgrade.equals("false")) {
			String s = "您达到了晋升\"" + mUserBean.upgrade + "\"的条件，点击晋升";
			is_upgrade.setVisibility(View.VISIBLE);
			is_upgrade.setText(s);
			upgrade_linear.setVisibility(View.VISIBLE);
			IApplication.levelUp = false;
		} else {
			is_upgrade.setVisibility(View.INVISIBLE);
			upgrade_linear.setVisibility(View.GONE);
		}
	}

	private void showLevelUpView() {
		final int level = Integer.valueOf(mUserBean.level);
		// 1,
		int[] ids = { 0, R.layout.bk_dialog_lexiang,
				R.layout.bk_dialog_dulijingjiren,
				R.layout.bk_dialog_jingyinglingxiu,
				R.layout.bk_dialog_rongyaodongshi };

		View v = View.inflate(this, ids[level], null);
		CheckBox ck = (CheckBox) v.findViewById(R.id.ckbtn_ok);
		final AlertDialog ad = new AlertDialog.Builder(this)
				.setTitle(mUserBean.upgrade + "晋升协议")
				.setPositiveButton("升级", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						if (isGreed) {
							if (level == 4
									|| mUserBean.upgrade.contains("荣耀董事")) {
								IApplication.showToast("升级成荣耀董事只能人工审核通过");
								return;
							}
							new UserUpgrade(ctx);
						}
					}
				})
				.setView(v)
				.setNeutralButton("暂不升级",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface arg0, int arg1) {
							}
						}).show();
		ck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				isGreed = arg1;
			}
		});
	}

	private boolean isGreed = false;

	private void updateUI() {
		if (mUserBean == null) {
			center_balance.setText("");
			center_cash.setText("");
			center_unclear.setText("");
			center_name.setText("");
			image.setImageResource(R.drawable.user_avar_bg);
			center_vip.setVisibility(View.INVISIBLE);
			user_leftmoney.setText("");
		} else {
			user_leftmoney.setText("账户余额：" + mUserBean.money);
			center_vip.setVisibility(View.VISIBLE);
			center_vip.setText("" + levelStr[Integer.valueOf(mUserBean.level)]);

			if (mUserBean.history_cash != null
					&& mUserBean.history_cash.equals("0")) {
				center_cash.setText("0.00");
			} else {
				center_cash.setText(mUserBean.history_cash);
			}
			center_unclear.setText(mUserBean.amount);
			center_name.setText(mUserBean.username);
			try {
				app().imageLoader.displayImageNoCache(mUserBean.avatar, image);
			} catch (Exception e) {
				image.setBackgroundResource(R.drawable.user_avar_bg);
			}

			try {
				float m = Float.valueOf(mUserBean.money);
				float c = Float.valueOf(mUserBean.history_cash);
				if (mUserBean.sales_cash.equals("0")) {
					center_balance.setText("0.00");
				} else {
					center_balance.setText("" + mUserBean.sales_cash);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private String[] levelStr = { "    ", "注册会员", "乐享会员", "独立经纪人", "精英领袖",
			"荣耀董事" };

	/************************************************************************************
	 *  
	 ************************************************************************************/

	/**
	 * 个人信息
	 */
	class GetUserInfo extends WKAsyncTaskPro {
		public GetUserInfo(Context context) {
			super(context, false, false);
		}

		@Override
		protected String doInBackground(boolean... isLocal) {
			return app().net.userInfo(isLocal);
		}

		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			try {

				Type cvbType = new TypeToken<BKBaseBean<UserInfoBean>>() {
				}.getType();
				Gson gson = new Gson();
				BKBaseBean<UserInfoBean> base = gson.fromJson(result, cvbType);
				Log.e("wj", "status : " + base.status);
				if (base.status == 1) {

					// 判断数据合法性
					if (base.data == null || base.data.userid.equals("")) {
						mUserBean = null;
						app().userInfo = null;
						app().setLoginSession("");
						updateUI();
						return;
					}

					mUserBean = base.data;
					app().userInfo = base.data;
					checkLevel();
				} else {
					mUserBean = null;
					app().userInfo = null;
				}
				updateUI();

			} catch (Exception e) {
				e.printStackTrace();
				IApplication.showToast("请重新登录");
				mUserBean = null;
				app().userInfo = null;
				app().setLoginSession("");
				updateUI();
			}
		}
	}

	/**
	 * 获取头像的url地址
	 */
	class GetAvatorUrl extends WKAsyncTaskPro {
		public GetAvatorUrl(Context context) {
			super(context);
		}

		@Override
		protected String doInBackground(boolean... params) {
			return app().net.getAvatorUrl();
		}

		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			Type cvbType = new TypeToken<BKBaseBean>() {
			}.getType();
			Gson gson = new Gson();
			BKBaseBean base = gson.fromJson(result, cvbType);
			if (base.status == 1) {
				String baseUrl = base.data.toString();
				L.wj("" + baseUrl);
				urlUpAvator = new String(new Base64().decode("" + baseUrl));
				L.wj("" + urlUpAvator);
				new Avator(activity).showSelection(header);
			} else {
				Toast.makeText(ctx, "获取失败", 0).show();
			}
		}
	}

	/**
	 * 用户晋升接口
	 */
	class UserUpgrade extends WKAsyncTaskPro {
		public UserUpgrade(Context context) {
			super(context);
		}

		@Override
		protected String doInBackground(boolean... params) {
			return app().net.userUpgrade();
		}

		@Override
		protected void doOnPostExecute(String result, boolean isLocal) {
			Type cvbType = new TypeToken<BKBaseBean>() {
			}.getType();
			Gson gson = new Gson();
			BKBaseBean base = gson.fromJson(result, cvbType);
			if (base.status == 1) {
				IApplication.showToast("" + base.info);
				center_vip.setText("" + mUserBean.upgrade);
				center_vip.setVisibility(View.VISIBLE);
				upgrade_linear.setVisibility(View.GONE);
			} else {
				IApplication.showToast("" + base.info);
				center_vip.setVisibility(View.INVISIBLE);
			}
		}
	}

	/**************************************************************************************/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		new WKPhotoUtil().onActivityResult(activity, requestCode, resultCode,
				data, new IImageCallBack() {
					@Override
					public void onResult(final Bitmap bitmap, String path) {
						// Toast.makeText(ctx,
						// "path : "+path+" - url :"+urlUpAvator, 0).show();
						if (bitmap != null) {
							URL url = null;
							try {
								url = new URL("" + urlUpAvator);
							} catch (MalformedURLException e1) {
								e1.printStackTrace();
							}
							final BKUploadUtil uploadUtile = new BKUploadUtil();
							uploadUtile.avatorUploadUrl(url, path,
									new UploadCallBack() {
										@Override
										public void success(String result) {
											L.wj("bitMap result : " + result);
											image.setImageBitmap(bitmap);
										}

										@Override
										public void failed() {
											WKApplication.showMsg("上传出错");
										}
									}, new Handler() {
										@Override
										public void handleMessage(Message msg) {
											super.handleMessage(msg);
											L.wj("message :" + msg.what + " - "
													+ msg.obj);
											// image.setImageBitmap(((Bitmap)msg.obj));
											if (msg.what == 1) {
												uploadUtile.callback
														.success(msg.obj
																.toString());
												// if
												// (msg.obj.toString().contains("success")){
												// uploadUtile.callback.success("成功！！！");
												// }else{
												// uploadUtile.callback.failed();
												// }
											} else {
												uploadUtile.callback.failed();
											}
										}
									});
						}
					}
				});
		super.onActivityResult(requestCode, resultCode, data);
	}
}
